<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="歌曲名称" prop="name">
        <el-input
          v-model="queryParams.name"
          clearable
          placeholder="请输入歌曲名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker
          v-model="dateRange"
          end-placeholder="结束日期"
          range-separator="-"
          start-placeholder="开始日期"
          style="width: 240px"
          type="daterange"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="类型" prop="status">
        <el-select
          v-model="queryParams.type"
          clearable
          placeholder="类型"
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_song_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:song:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:song:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:song:export']"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:song:export']"
          icon="el-icon-download"
          plain
          size="mini"
          type="info"
          @click="handleDownloadTemplate"
        >下载模板
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload :action="upload.url" :before-upload="beforeUpload" :data="uploadData" :headers="upload.headers"
                   :on-error="onError"
                   :on-success="onSuccess" :show-file-list="false" accept=".xlsx,.xls" method="post">
          <el-button size="mini">
            <i class="el-icon-upload"></i>
            导入
          </el-button>
        </el-upload>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="songList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="歌曲名称" prop="name"/>
      <el-table-column align="center" label="歌手名称" prop="singer" width="260"/>
      <el-table-column label="类型" prop="type">
        <template slot-scope="scope">
          <span v-if="scope.row.type === 1">歌曲</span>
          <span v-if="scope.row.type === 2">舞蹈</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="日期" prop="date" width="160">
      </el-table-column>
      <el-table-column align="center" label="排序" prop="orderNum" width="160">
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:song:edit']"
            icon="el-icon-edit"
            size="mini"
            type="success"
            style="width: 70px"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            v-hasPermi="['system:song:remove']"
            icon="el-icon-delete"
            size="mini"
            type="danger"
            style="width: 70px"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改【歌单】对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="歌曲名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入歌曲名称"/>
        </el-form-item>
        <el-form-item label="类型" style="width: 1080px">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 380px">
            <el-option
              v-for="dict in dict.type.sys_song_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" style="width: 1080px">
          <el-date-picker
            v-model="form.date"
            placeholder="日期"
            range-separator="-"
            style="width: 380px"
            type="date"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addSong, delSong, getSong, listSong, updateSong} from "@/api/system/song";
import {parseTime} from "@/utils/ruoyi";
import {getToken} from "@/utils/auth";

export default {
  name: "Song",
  dicts: ['sys_song_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 歌单表格数据
      songList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入按钮的文本
      importDataText: '导入数据',
      // 导入按钮的图标
      importDataIcon: 'el-icon-upload2',
      // 导入按钮是否被禁用
      importDisabled: false,
      // 日期范围
      dateRange: [],
      date: '',
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + `/system/song/importExcel`
      },
      uploadData: {
        date: this.date
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        date: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "歌曲名称不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    /** 查询【歌单】列表 */
    getList() {
      this.loading = true;
      listSong(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.songList = response.rows;
        console.log(response.rows)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        singer: null,
        url: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        type: null,
        date: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加歌单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSong(id).then(response => {
        this.form = response.data;
        if (this.form.type === 1) {
          this.form.type = "歌曲"
        } else {
          this.form.type = "舞蹈"
        }
        this.open = true;
        this.title = "修改歌单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.type === '歌曲') {
              this.form.type = 1
            }
            if (this.form.type === '舞蹈') {
              this.form.type = 2
            }
            updateSong(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSong(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除歌单编号为"' + ids + '"的数据项？').then(function () {
        return delSong(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/song/export', {
        ...this.queryParams
      }, `song_${new Date().getTime()}.xlsx`)
    },
    /** 导出按钮操作 */
    handleDownloadTemplate() {
      this.download('system/song/download', {
        ...this.queryParams
      }, `歌单模板.xlsx`)
    },
    onError() {
      this.importDataText = '导入数据';
      this.importDataIcon = 'el-icon-upload2';
      this.importDisabled = false;
      this.resetQuery();
      this.$message.success("导入失败！");
    },
    // 导入文件成功后回调
    onSuccess() {
      // 成功后文本修改为原来的导入数据
      this.importDataText = '导入数据';
      // 图标修改
      this.importDataIcon = 'el-icon-upload2';
      // 将上传组件改为允许使用
      this.importDisabled = false;
      // 调用刷新数据的方法
      this.resetQuery();
      // message 弹出消息
      this.$message.success("导入成功！");
    },
    // 上传文件调用
    beforeUpload() {
      // 将文本修改为正在导入
      this.importDataText = '正在导入';
      // 修改其图标
      this.importDataIcon = 'el-icon-loading';
      // 将其上传组件暂时禁用
      this.importDisabled = true;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
